package com.jqk.shop_product.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jqk.shop_product.bean.Product;
import com.jqk.shop_product.bean.TblOrderEvent;
import com.jqk.shop_product.service.ProductService;
import com.jqk.shop_product.service.TblOrderEventService;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.json.Json;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author jqk
 * @date 2020/7/30
 */
@Component
public class ProduceTask {

    @Autowired
    private TblOrderEventService tblOrderEventService;

    @Autowired
    private ProductService productService;


    @Scheduled(cron="0/5 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void task(){
        // 查出事件表中状态为 3 的事件
        List<TblOrderEvent> events = tblOrderEventService.query().eq("order-type", "3").list();
        if(CollectionUtils.isNotEmpty(events)){
            // 将事件状态修改，并封装成消息类型
            List<Product> products=new ArrayList<>(events.size());
            List<TblOrderEvent> eventList = events.stream().peek(item -> {
                products.add(JSONObject.parseObject(item.getContent(),Product.class));
                item.setOrderType("4");
            }).collect(Collectors.toList());
            // 修改数据库中的事件
            tblOrderEventService.saveOrUpdateBatch(eventList);
            //业务处理
            Map<String, List<Product>> collect = products.stream().collect(Collectors.groupingBy(Product::getPname));
            products.clear();
            for (String pname : collect.keySet()) {
                Product product = productService.query().eq("pname", pname).one();
                product.setStock(product.getStock()-collect.get(pname).size());
                products.add(product);
            }
            productService.saveOrUpdateBatch(products);
        }
    }

}
